24.6.1. Loading YAML
24.6.1. 加载YAML
Spring框架提供两个便利的类用于加载YAML文档,YamlPropertiesFactoryBean会将YAML加载为Properties,YamlMapFactoryBean会将YAML加载为Map。
例如,下面的YAML文档:
environments:
    dev:
        url: http://dev.example.com
        name: Developer Setup
    prod:
        url: http://another.example.com
        name: My Cool App
会被转化为如下属性:
environments.dev.url=http://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=http://another.example.com
environments.prod.name=My Cool App
YAML列表被表示成使用[index]间接引用作为属性keys的形式,例如下面的YAML:
my:
   servers:
       - dev.example.com
       - another.example.com
将会转化到这些属性:
my.servers[0]=dev.example.com
my.servers[1]=another.example.com
使用Spring DataBinder工具集绑定这些属性(这是@ConfigurationProperties做的事)时,你需要确保目标bean有个java.util.List或Set类型的属性,并且需要提供一个setter或使用可变的值初始化它,比如,下面的代码将绑定之前的属性:
@ConfigurationProperties(prefix="my")
public class Config {
    private List<String> servers = new ArrayList<String>();
    public List<String> getServers() {
        return this.servers;
    }
}
注 当多个位置配置了列表,重写通过替换整个列表发生。在之前的例子里,当在几个地方定义了my.servers,来自PropertySource拥有更高优先级的整个列表会重写那个列表的任何其它的配置。可以使用逗号分隔的列表和YAML列表来完全重写列表的内容。